<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-02-04 21:42:14
 * Desc:
 */

namespace app\admin\controller\wish;

use app\admin\controller\adminAuthController;
use app\api\service\GoodsService;
use app\base\service\Pay\{WxPayService, OrderService};
use app\base\model\order\Order;
use app\base\model\address\UserAddressInfo;
use app\base\model\user\{User, UserAccount};
use app\base\model\goods\{GoodsBaseInfo, GoodsGroupInfo, GoodsGroupJoinInfo, GoodsIntroduceInfo};
use app\base\model\system\SystemConfig;
use app\core\cache\RedisKeys;
use app\core\exception\{BusinessException, ErrorCode};
use app\core\util\PreVentRepeatSubmitUtil;
use app\core\log\Log4dd;
use think\Request;

class WishController extends adminAuthController
{

    public function getWishList()
    {
        $size = input('page_size/d', 20);
        $page = input('page/d', 1);
        $where = [];
        $order = [];
        $group_state = input('group_state/d', 0);
        if ($group_state > 0) {
            $where['gp.group_state'] = $group_state;
        }

        $is_robot = input('is_robot/d', 0);
        if ($is_robot) {
            $where['user.account_type'] = ['<>', User::ACCOUNT_TYPE_ROBOT];
        }

        $gender = input('gender/d', 0);
        if ($gender) {
            $where['user.gender'] = $gender;
        }

        $goods_id = input('goods_id/d', 0);
        if ($goods_id) {
            $where['gp.goods_id'] = $goods_id;
        }

        $search_num = input('search_num/s', '');

        $query_string = '';

        //group_id user_id
        if ($search_num) {
            $query_string = "gp.group_id = {$search_num} or user.user_id = {$search_num}";
        }

        $start_time = input('start_time/s', '');
        $end_time = input('end_time/s', '');
        if ($start_time && $end_time) {
            $where['gp.create_time'] = ['BETWEEN', [$start_time, $end_time]];;
        } elseif ($start_time) {
            $where['gp.create_time'] = ['>=', $start_time];
        } elseif ($end_time) {
            $where['gp.create_time'] = ['<=', $end_time];
        }

        $sort = input('sort/d', 0);

        switch ($sort) {
            case 1:
                $order = ['gp.create_time' => 'asc'];
                break;
            case 2:
                $order = ['gp.create_time' => 'desc'];
                break;
            case 3:
                $order = ['gp.success_time' => 'asc'];
                $where['gp.group_state'] = GoodsGroupInfo::GROUP_SUCCESS_STATE;
                break;
            case 4:
                $order = ['gp.success_time' => 'desc'];
                $where['gp.group_state'] = GoodsGroupInfo::GROUP_SUCCESS_STATE;
                break;
            case 5:
                $order = ['wait_support_time' => 'desc'];
                $where['gp.group_state'] = GoodsGroupInfo::GROUP_RUN_STATE;
                break;
            case 6:
                $order = ['wait_support_time' => 'asc'];
                $where['gp.group_state'] = GoodsGroupInfo::GROUP_RUN_STATE;
                break;
            default:
                $order = ['gp.create_time' => 'desc'];
                break;
        }


        $data = GoodsGroupInfo::adminGetWishList($where, $query_string, $order, $page, $size);
        return $this->successReturn($data);
    }

    public function adminInitiateWish()
    {
        $user_id = input('robot_user_id/d', 0);

        if(empty($user_id)){
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '机器人user_id不能为空');
        }

        $account_type = User::getUserFieldById($user_id, 'account_type');

        $account_type = (int)$account_type;

        if($account_type != User::ACCOUNT_TYPE_ROBOT){
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '此账号非机器人');
        }

        //防重复提交
        PreVentRepeatSubmitUtil::check(RedisKeys::getInitiateWishKey($user_id));

        $goods_id = input('goods_id/d', 0);

        if (empty($goods_id)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '商品id不能为空');
        }

        $my_wish = input('my_wish/s', '', 'trim');

        empty($my_wish) && $my_wish = SystemConfig::getSystemConfigByName('default_wish', '');

        $address_id = input('address_id/d', 0);

        /*if (empty($address_id)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '地址id不能为空');
        }

        if (!UserAddressInfo::addressIsExists(['address_id' => $address_id, 'user_id' => $user_id])) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '地址信息不存在');
        }*/

        try {

            $wish_data = [
                'my_wish' => $my_wish,
            ];
            $res = GoodsService::instance()->initiateWish($user_id, $goods_id, $wish_data);

            $wish_coin_num = UserAccount::getWishCoinNumByUserId($user_id);
            if ($res && isset($res['group_id']) && $res['group_id']) {
                $wish_info = GoodsService::instance()->getWishInfo($user_id, $res['group_id']);
                //绑定收货信息
                //GoodsService::instance()->bindAddress($user_id, $res['group_id'], $address_id);
                return $this->successReturn([
                    'group_id' => $res['group_id'],
                    'wish_coin_num' => $wish_coin_num,
                    'wish_info' => $wish_info
                ]);
            } else {
                return $this->errorReturn(ErrorCode::COMMON_ERROR, '发起心愿失败，请稍后再试');
            }

        } catch (BusinessException $e) {
            Log4dd::info("发起心愿失败:{$e->getMessage()}", func_get_args(), $e);
            return $this->errorReturn($e->getCode(), $e->getMessage());
        }
    }

    public function adminSupportWish()
    {

        $user_id = input('robot_user_id/d', 0);

        if(empty($user_id)){
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '机器人user_id不能为空');
        }

        $account_type = User::getUserFieldById($user_id, 'account_type');

        $account_type = (int)$account_type;

        if($account_type !== User::ACCOUNT_TYPE_ROBOT){
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '此账号非机器人');
        }

        //防重复提交
        PreVentRepeatSubmitUtil::check(RedisKeys::getSupportWishKey($user_id));

        Log4dd::info("小程序支持TA人心愿", Request::instance()->param(false));

        $app_id = input('app_id/s', 'wx5a158ad716b5e959');

        if (empty($app_id)) {
            throw new BusinessException(ErrorCode::MINI_PROGRAM_LACK_PARAMS, 'app_id不能为空');
        }

        //支持一次支持多商品
        $group_ids = input('group_ids/s', '');

        $group_ids = stringToArray($group_ids, ',', 'intval');

        if (empty($group_ids)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '要支持的group_id为空');
        }

        if (count($group_ids) == 1) {
            $group_id = current($group_ids);
            $group_info = GoodsGroupInfo::find($group_id);

            if (empty($group_info)) {
                throw new BusinessException(ErrorCode::DATA_NOT_FOUND, '未查询到心愿信息');
            }

            if ($group_info['user_id'] == $user_id) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, '不能支持自己的心愿');
            }

            if ($group_info['group_state'] == GoodsGroupInfo::GROUP_CANCEL_STATE) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, '该心愿已经被发起者取消');
            }

            if ($group_info['group_state'] == GoodsGroupInfo::GROUP_SUCCESS_STATE) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, '来晚了一步，该心愿的支持人数已经达标啦~');
            }

            if ($group_info['need_people'] > 0 && $group_info['join_people'] >= $group_info['need_people']) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, '来晚了一步，该心愿的支持人数已经达标啦~');
            }

            //判断自己是否已支持
            $join_info = GoodsGroupJoinInfo::getGroupJoinUserInfoByUserId($group_id, $user_id);

            if ($join_info) {
                throw new BusinessException(ErrorCode::COMMON_ERROR, '您已经支持过一次啦~');
            }
        }


        $params = [
            'pay_way' => Order::PAY_WAY_ADMIN,
            'pay_mode' => Order::PAY_MODE_WX_PAY,
            'app_id' => $app_id
        ];

        try {
            $order_info = GoodsService::instance()->supportWish($user_id, $account_type, $group_ids, $params);
            OrderService::orderSuccess($user_id, 0, $order_info['out_trade_no']);//直接说订单处理成功了
            $this->errorReturn(ErrorCode::COMMON_SUCCESS, '支持成功');
        } catch (BusinessException $e) {
            Log4dd::info("支持TA人下单失败:{$e->getMessage()}", func_get_args(), $e);
            $this->errorReturn($e->getCode(), '下单失败');
        }
    }

    public function adminCancelWish()
    {
        $group_id = input('group_id/d', '');

        if (empty($group_id)) {
            throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS, '要支持的group_id为空');
        }

        try {
            GoodsService::cancelWish($this->adminId, $group_id, true);
            return $this->successReturn([], '取消成功，心愿值已返还到您的账户');
        } catch (BusinessException $e) {
            Log4dd::info("取消心愿失败:{$e->getMessage()}", func_get_args(), $e);
            return $this->errorReturn($e->getCode(), $e->getMessage());
        }
    }

}